<template>
  <div class="study-material">
    <!-- 上传区域 -->
    <div v-if="[1].includes(data.user.userType)">
      <el-card v-if="isAdmin" class="upload-card">
        <template #header>
          <div class="card-header">
            <span>上传学习资料</span>
          </div>
        </template>

        <el-form :model="form" label-width="100px">
          <el-form-item label="资料标题" required>
            <el-input v-model="form.title" placeholder="请输入资料标题"/>
          </el-form-item>

          <el-form-item label="资料类型" required>
            <el-select v-model="form.materialType" placeholder="请选择资料类型">
              <el-option label="党课资料" :value="1"/>
              <el-option label="团课资料" :value="2"/>
              <el-option label="其他资料" :value="3"/>
            </el-select>
          </el-form-item>

          <el-form-item label="资料说明">
            <el-input v-model="form.content" type="textarea" rows="3" placeholder="请输入资料说明"/>
          </el-form-item>

          <el-form-item label="上传文件" required>
            <el-upload
                class="upload-demo"
                :action="uploadUrl"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
                :file-list="fileList"
            >
              <el-button type="primary">选择文件</el-button>
              <template #tip>
                <div class="el-upload__tip">只能上传 PDF 文件</div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSubmit">发布</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 资料列表 -->
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span>学习资料列表</span>
          <div class="search-area">
            <el-input
                v-model="searchForm.title"
                placeholder="资料标题"
                style="width: 200px; margin-right: 10px"
                clearable
            />
            <el-select
                v-model="searchForm.materialType"
                placeholder="资料类型"
                style="width: 150px; margin-right: 10px"
                clearable
            >
              <el-option label="党课资料" :value="1"/>
              <el-option label="团课资料" :value="2"/>
              <el-option label="其他资料" :value="3"/>
            </el-select>
            <el-button type="primary" @click="loadData">查询</el-button>
            <el-button type="warning" plain @click="reset">重置</el-button>
          </div>
        </div>
      </template>

      <el-table :data="data.list" v-loading="loading">
        <el-table-column prop="title" label="资料标题"/>
        <el-table-column prop="materialType" label="资料类型" width="120">
          <template #default="scope">
            {{ getMaterialTypeName(scope.row.materialType) }}
          </template>
        </el-table-column>
        <el-table-column prop="content" label="资料说明" show-overflow-tooltip/>
        <el-table-column prop="downloadCount" label="下载次数" width="100"/>
        <el-table-column prop="createTime" label="上传时间" width="180"/>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <!-- 修改下载按钮样式 -->
            <el-button
                type="primary"
                :icon="Download"
                @click="handleDownload(scope.row)"
            >
              下载
            </el-button>
            <el-button
                v-if="isAdmin"
                :type="scope.row.status === 1 ? 'danger' : 'success'"
                @click="handleChangeStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '下架' : '上架' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="data.pageNum"
            v-model:page-size="data.pageSize"
            :total="data.total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage} from 'element-plus'
import request from '@/utils/request'
import {getUserInfo} from "@/utils/auth";
import {Download} from '@element-plus/icons-vue'

const isAdmin = ref(false) // 根据实际登录用户角色设置
const loading = ref(false)
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload'
const fileList = ref([])

const data = reactive({
  list: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  user: getUserInfo() || {},
})

const form = reactive({
  title: '',
  content: '',
  materialType: null,
  fileUrl: '',
  branchId: null,
  creatorId: null
})

const searchForm = reactive({
  title: '',
  materialType: null
})

// 加载数据

// 修改加载数据方法，传入isAdmin参数
const loadData = async () => {
  loading.value = true
  try {
    const res = await request.get('/studyMaterial/page', {
      params: {
        ...searchForm,
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        isAdmin: isAdmin.value
      }
    })
    data.list = res.data.list
    data.total = res.data.total
  } catch (error) {
    ElMessage.error('获取资料列表失败')
  } finally {
    loading.value = false
  }
}

const reset = () => {
  searchForm.title = ''
  searchForm.materialType = null
  loadData()
}
// 文件上传相关方法
const beforeUpload = (file) => {
  const isPDF = file.type === 'application/pdf'
  if (!isPDF) {
    ElMessage.error('只能上传 PDF 文件！')
    return false
  }
  return true
}

const handleUploadSuccess = (res) => {
  form.fileUrl = res.data
  ElMessage.success('文件上传成功')
}

// 提交表单
const handleSubmit = async () => {
  if (!form.title || !form.materialType || !form.fileUrl) {
    ElMessage.warning('请填写必填项')
    return
  }

  try {
    form.creatorId = getUserInfo().id
    await request.post('/studyMaterial/add', form)
    ElMessage.success('发布成功')
    await loadData()
    // 重置表单
    Object.assign(form, {
      title: '',
      content: '',
      materialType: null,
      fileUrl: ''
    })
    fileList.value = []
  } catch (error) {
    ElMessage.error('发布失败')
  }
}

// 下载文件

// 修改下载方法，添加下载次数统计
const handleDownload = async (row) => {
  try {
    // 先增加下载次数
    await request.post(`/studyMaterial/incrementDownload/${row.id}`)
    // 然后下载文件
    window.open(row.fileUrl)
    // 刷新列表以更新下载次数显示
    await loadData()
  } catch (error) {
    ElMessage.error('下载失败')
  }
}

// 更改状态
// 修改状态变更方法
const handleChangeStatus = async (row) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1
    await request.post(`/studyMaterial/changeStatus/${row.id}`, null, {
      params: {status: newStatus}
    })
    ElMessage.success(newStatus === 1 ? '上架成功' : '下架成功')
    // 更新本地数据
    row.status = newStatus
    // 重新加载数据
    await loadData()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 获取资料类型名称
const getMaterialTypeName = (type) => {
  const types = {
    1: '党课资料',
    2: '团课资料',
    3: '其他资料'
  }
  return types[type] || '未知类型'
}

// 分页方法
const handleSizeChange = (val) => {
  data.pageSize = val
  loadData()
}

const handleCurrentChange = (val) => {
  data.pageNum = val
  loadData()
}

onMounted(() => {
  // 获取用户信息，设置 isAdmin
  const user = getUserInfo() || {}
  isAdmin.value = [1].includes(user.userType)
  loadData()
})
</script>

<style scoped>
.study-material {
  padding: 20px;
}

.el-button [class*='el-icon'] + span {
  margin-left: 6px;
}

.upload-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
